package sysmodels

import (
	"errors"
	"github.com/astaxie/beego/orm"
	"myadmin/sys/field"
	"strings"
)

type SysRole struct {
	Id       int            `orm:"" json:"id"`
	RoleName string         `orm:"size(50);unique" form:"rolename" json:"rolename"` //英文 账号
	Name     string         `orm:"size(50);unique" form:"name" json:"name"`           //权限名称
	Describe string         `orm:"size(50)" form:"describe" json:"describe"`       //描述
	Status   bool           `orm:"default(1)" form:"status" json:"status"`        //是否有效
	AuthList field.JsonList `orm:"type(text)" form:"authlist" json:"authlist"`      //auth 所有authname json数据 需要转换
}

func NewRole() *SysRole {
	return &SysRole{
		Status: true,
	}
}

//添加
func (this *SysRole) Add() error {
	o := orm.NewOrm()
	//验证auth是否存在
	for _, v := range this.AuthList {
		if t := o.QueryTable(AUTHTABLE).Filter("AuthName", v).Exist(); !t {
			return errors.New(strings.Join([]string{v, "权限不存在"}, ""))
		}
	}
	_, err := o.Insert(this)
	if err != nil && strings.Contains(err.Error(), "1062") {
		return errors.New("角色标识已经存在")
	}
	return err
}

//更新
func (this *SysRole) Update(keys []string) error {
	o := orm.NewOrm()
	if this.AuthList != nil {
		for _, v := range this.AuthList {
			if t := o.QueryTable(AUTHTABLE).Filter("AuthName", v).Exist(); !t {
				return errors.New(strings.Join([]string{v, "权限不存在"}, ""))
			}
		}
	}
	_,err:=o.Update(this,keys...)
	return err
}


//根据id查询
func (this *SysRole) GetById() error {
	o := orm.NewOrm()
	err := o.Read(this)
	return err
}


//查询 根据rolename查询
func(this *SysRole) GetByRoleName() error{
	o:=orm.NewOrm()
	err:=o.Read(this,"RoleName")
	return err
}

//查询2 query
func (this *SysRole) Query(limit, page int) ([]*SysRole, int64) {
	qs := orm.NewOrm().QueryTable(ROLETABLE)
	var roles []*SysRole
	if this.RoleName != "" {
		qs = qs.Filter("RoleName__icontains", this.RoleName)
	}
	qs.Limit(limit, (page-1)*limit).OrderBy("id").All(&roles)
	cnt, _ := qs.Limit(limit, (page-1)*limit).Count()
	return roles, cnt
}

//唯一角色标识是否存在
func(this *SysRole) IsExistByRoleName() bool{
	o:=orm.NewOrm()
	return o.QueryTable(ROLETABLE).Filter("RoleName", this.RoleName).Exist()
}


//删除by id
func (this *SysRole) DeleteById() (int64, error) {
	o := orm.NewOrm()
	row, err := o.Delete(this, "id")
	return row, err
}
